package app.foodnote;


import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import app.foodnote.db.FoodNotesDataSource;
import app.foodnote.db.MySQLiteHelper;


public class FoodPlaces extends ListActivity {
	 public final static String ID_EXTRA = "app.foodnote._ID";
	 
	 private final int CONTEXT_MENU_ID = 1;
     private IconContextMenu iconContextMenu = null;
     
     private final int MENU_ITEM_1_ACTION = 1;
     private final int MENU_ITEM_2_ACTION = 2;
     private final int MENU_ITEM_3_ACTION = 3;
     private final int MENU_ITEM_4_ACTION = 4;
     private final int MENU_ITEM_5_ACTION = 5;
     
     
	 private FoodNotesDataSource datasource;
	 private SharedPreferences pref=null;
	 Cursor cursor;
	 
	 String Id = null;
	 
	 // Progress dialog
     ProgressDialog pDialog;
     
     AlertDialogManager alert = new AlertDialogManager();
     
     // Google Places
     GooglePlaces googlePlaces;
  
     // Places List
     PlacesList nearPlaces;
	 ///////////////////////////////////////////////////////////////////////
	 
	 @Override
	 public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setTitle("Danh Sách Món Ăn");
	        setContentView(R.layout.form_places);
	        Resources res = getResources();
	        pref = PreferenceManager.getDefaultSharedPreferences(this);
			initList();
		    pref.registerOnSharedPreferenceChangeListener(prefListener);
	       
	        
	       
	        // Search foods
			Intent intentSearch = getIntent();
			if(Intent.ACTION_SEARCH.equals(intentSearch.getAction())){
				String query = intentSearch.getStringExtra(SearchManager.QUERY);
				pref = PreferenceManager.getDefaultSharedPreferences(this);
				doMySearch(query);
			    pref.registerOnSharedPreferenceChangeListener(prefListener);
			} 
			else{
				//Toast.makeText(getApplicationContext(), "aaa", Toast.LENGTH_LONG).show();
				 pref = PreferenceManager.getDefaultSharedPreferences(this);
			     initList();
			     pref.registerOnSharedPreferenceChangeListener(prefListener);
			}
			
			/*new LoadFoodsList().execute();*/
			 //init the menu
	        iconContextMenu = new IconContextMenu(this, CONTEXT_MENU_ID);
	        iconContextMenu.addItem(res, "Cập Nhật", R.drawable.update, MENU_ITEM_1_ACTION);
	        iconContextMenu.addItem(res, "Xóa", R.drawable.delete, MENU_ITEM_2_ACTION);
	        iconContextMenu.addItem(res, "Chi Tiết", R.drawable.detail, MENU_ITEM_3_ACTION);
	        iconContextMenu.addItem(res, "Món Ăn Xung Quanh", R.drawable.food_around, MENU_ITEM_4_ACTION);
	        iconContextMenu.addItem(res, "Hiển Thị Trên Bản Đồ", R.drawable.showmap, MENU_ITEM_5_ACTION);
	        
	        iconContextMenu.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
                public void onClick(int menuId) {
                        switch(menuId) {
                        case MENU_ITEM_1_ACTION:
                        	Intent intentFoodPlace = new Intent(FoodPlaces.this, FoodAdd.class);
            				intentFoodPlace.putExtra(ID_EXTRA, Id);
            				startActivity(intentFoodPlace);
                            break;
                        case MENU_ITEM_2_ACTION:
                            datasource = new FoodNotesDataSource(getApplicationContext());
                            datasource.openToWrite();
                            datasource.deleteFoodNote(Id);
                            datasource.close();
                            initList();
                            Toast.makeText(getApplicationContext(), "Bạn đã xóa thành công món ăn với id " + Id, Toast.LENGTH_LONG).show();
                            break;
                        case MENU_ITEM_3_ACTION:
                        	Intent detail = new Intent(FoodPlaces.this, DetailActivity.class);
                        	detail.putExtra(ID_EXTRA, Id);
                            startActivity(detail);
                            break;
                        case MENU_ITEM_4_ACTION:
                        	datasource.openToRead();
                    		Cursor cs = datasource.getFoodNoteById(Id);
                    		cs.moveToFirst();
                    		double GOOGLE_API_LAT_EXTRA = datasource.getLatitude(cs);
                    		double GOOGLE_API_LOG_EXTRA = datasource.getLongitude(cs);
                    		cs.close();
                    		datasource.close();
                    		Intent googleAPI = new Intent(FoodPlaces.this, ShowPlacesList.class);
                    		googleAPI.putExtra("GOOGLE_API_LAT_EXTRA", GOOGLE_API_LAT_EXTRA);
                    		googleAPI.putExtra("GOOGLE_API_LOG_EXTRA", GOOGLE_API_LOG_EXTRA);
                    		startActivity(googleAPI);
                        	break;
                        case MENU_ITEM_5_ACTION:
                        	datasource.openToRead();
                    		Cursor c = datasource.getFoodNoteById(Id);
                    		c.moveToFirst();
                    		double LAT_EXTRA = datasource.getLatitude(c);
                    		double LOG_EXTRA = datasource.getLongitude(c);
                    		c.close();
                    		datasource.close();
                    		Intent intentMaps = new Intent(FoodPlaces.this, LocationActivity.class);
                    		intentMaps.putExtra("LAT_EXTRA", LAT_EXTRA);
                    		intentMaps.putExtra("LOG_EXTRA", LOG_EXTRA);
                    		startActivity(intentMaps);
                            break;
                        }
                }

	        });
			
	 }
	
	private void doMySearch(String query) {
		// TODO Auto-generated method stub
		datasource = new FoodNotesDataSource(this);
        datasource.openToRead();
        if (cursor!= null) {
            stopManagingCursor(cursor);
           cursor.close();
          }
        cursor = datasource.getSearchAll(query);
	    startManagingCursor(cursor);
	    String[] from = new String[] {MySQLiteHelper.FOOD_NAME, MySQLiteHelper.ADDRESS};
	    int[] to = new int[] {R.id.foodname, R.id.address};
	    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
        setListAdapter(adapter);
        
	}
	@Override
	protected void onListItemClick(ListView l, View v, int position, final long id) {
		
		this.Id = String.valueOf(id);
		showDialog(CONTEXT_MENU_ID);

	}
	@Override
	protected void onResume() {
		//datasource.openToRead();
		initList();
	    super.onResume();

	  }

	  @Override
	  protected void onPause() {
		  //datasource.close();
	      super.onPause();
	  }
	  @Override
	  protected void onDestroy(){
		  super.onDestroy();
		  datasource.close();
	  }
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(this).inflate(R.menu.form_places_option, menu);
		//setMenuBackground(); 
		return (super.onCreateOptionsMenu(menu));
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		if(item.getItemId()==R.id.add){
			startActivity(new Intent(FoodPlaces.this, FoodAdd.class));
			return true;
		}
		else if(item.getItemId()==R.id.setting){
			startActivity(new Intent(FoodPlaces.this, formsort.class));
			return true;
		}
		//else if(item.getItemId() == R.id.search) {
			//onSearchRequested();
			//return true;
		//}
		else if(item.getItemId() == R.id.back){
			Intent intent = new Intent(FoodPlaces.this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
			return true;
		}
		return (super.onOptionsItemSelected(item));
		
	}
	/**
     * create context menu
     */
    @Override
    protected Dialog onCreateDialog(int id) {
        if (id == CONTEXT_MENU_ID) {
                return iconContextMenu.createMenu("Menu");
        }
        return super.onCreateDialog(id);
    }

	//Khoi tao list
	private void initList(){
		datasource = new FoodNotesDataSource(this);
        datasource.openToRead();
        if (cursor!= null) {
            stopManagingCursor(cursor);
           cursor.close();
          }
        cursor = datasource.getAllEntrySort(pref.getString("sort", "foodname"));
	    startManagingCursor(cursor);
	    String[] from = new String[] {MySQLiteHelper.FOOD_NAME, MySQLiteHelper.ADDRESS};
	    int[] to = new int[] {R.id.foodname, R.id.address};
	    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
        setListAdapter(adapter);
        
	}
	
	private SharedPreferences.OnSharedPreferenceChangeListener prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
		
		public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
				String key) {
			// TODO Auto-generated method stub
			if(key.equals("sort")){
				initList();
			}
		}
	};
	
}
